package com.qiahao.service.impl;

import com.qiahao.bean.JwtUser;
import com.qiahao.bean.Role;
import com.qiahao.bean.User;
import com.qiahao.dto.UserDto;
import com.qiahao.mapper.RoleMapper;
import com.qiahao.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/4/2 0002.
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    public JwtUserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            Role role = roleMapper.findRoleById(user.getRole().getId());
            if (role != null) {
                authorityList.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String rawPassword = "111";
            user.setPassword(encoder.encode(rawPassword));
            return new JwtUser(user.getUsername(), user.getPassword(), authorityList);
        }
    }

}
